var fs = require('fs');
var mysql = require('mysql');
var superagent = require('superagent');

require('superagent-proxy')(superagent);

var mysqlCloudMusic = require('./config').mysqlCloudMusic;
var mysqlProxy = require('./config').mysqlProxy;

function run() {
    var ipList = [];
    var ipIndex = 0;

    function getIpList() {
        var connection = mysql.createConnection(mysqlProxy);
        var queryString = 'select * from ip_table1 where success_count>5 ' +
            'order by success_count desc limit 1000 ';
        connection.connect();
        connection.query(queryString, function (err, res) {
            if (err) {
                console.log(err);
                console.log();

            } else {
                ipList = res;
                for (var i = 0; i < 50; i++) {
                    main(i);
                }
            }
        });
        connection.end();
    }

    getIpList();

    function main(offset) {
        var ipItem;
        var retryCount = 0;

        var commentCount = -1;

        function getIpItem() {
            ipItem = ipList[ipIndex];
            if (ipItem.using) {
                ipIndex += 1;
                getIpItem();
            } else {
                ipItem.using = true;
                console.log('ipIndex');
                console.log(ipIndex);
                console.log();

                console.log(ipItem);
                console.log();

            }
        }
        getIpItem();

        function changeIpItem() {
            ipItem.using = false;
            if (ipIndex < ipList.length - 1) {
                ipIndex += 1;

            } else {
                ipIndex = 0;
            }
            getIpItem();
        }

        function getProxy(item) {
            var ip = item.ip;
            var port = item.port;
            return `http://${ip}:${port}`;
        }

        var song;

        function getSong() {
            var queryString = `SELECT * FROM song ORDER BY comment_version
                            LIMIT 1 offset ${offset};`
            var connection = mysql.createConnection(mysqlCloudMusic);
            connection.connect();
            connection.query(queryString, function (err2, res2) {
                if (err2) {
                    console.log(err2);
                } else {
                    // console.log(res2);
                    // console.log();

                    if (res2.length === 0) {
                        setTimeout(() => {
                            getSong();
                        }, 3600 * 1000);
                    } else {
                        song = res2[0];
                        console.log(song);
                        console.log();

                        getComment();
                    }
                }
            });
            connection.end();
        }
        getSong();

        function getComment() {
            var proxy = getProxy(ipItem);
            // console.log(song);

            const songId = song.id;
            let url = 'http://music.163.com/api/v1/resource/comments/R_SO_4_' + songId;
            superagent.get(url)
                .timeout(10000)
                .proxy(proxy)
                .end(function (err3, res3) {
                    console.log(url);
                    console.log();
                    console.log('ipIndex');

                    console.log(ipIndex);
                    console.log();

                    console.log('offset');
                    console.log(offset);
                    console.log(proxy);



                    if (err3) {
                        console.log(proxy);
                        console.log('http err');
                        if (retryCount < 3) {
                            retryCount += 1;
                            console.log('retry ' + retryCount);
                            console.log();

                            getComment();
                        } else {
                            changeIpItem();
                            getComment();
                        }
                    } else {
                        let text = res3.text;
                        fs.writeFile('html/comment.json', text, function () {
                            // 
                        });
                        if (/Cheating/g.test(text)) {
                            console.log('cheating');
                            changeIpItem();
                            getComment();
                        } else if (/资源不存在/g.test(text)) {
                            console.log('资源不存在');
                            console.log();
                            feedback();
                        } else {
                            let o = {};
                            try {
                                o = JSON.parse(res3.text);
                            } catch (error) {
                                console.log(error);
                            }
                            var hotComments = o.hotComments;
                            if (typeof hotComments !== 'undefined') {
                                commentCount = o.total;
                                console.log('total');
                                console.log(commentCount);
                                console.log();


                                if (hotComments.length > 0) {
                                    commentList = o.hotComments.map(v => {
                                        var id = v.commentId;
                                        var content = v.content;
                                        var time = v.time;
                                        var likedCount = v.likedCount;
                                        return [id, content, time, likedCount, songId];
                                    });

                                    upload();
                                } else {
                                    console.log('没有热门评论');
                                    console.log();
                                    feedback();
                                }
                            } else {
                                console.log(o);

                            }
                        }
                    }
                })
        }

        function upload() {
            var queryString = 'replace into comment (id,content,time,liked_count,song_id) values ?';

            var connection = mysql.createConnection(mysqlCloudMusic);
            connection.connect();
            connection.query(queryString, [commentList], function (err, res) {
                if (err) {
                    console.log(err);
                    console.log();

                } else {
                    console.log(res);
                    console.log();

                    feedback();
                }
            });
            connection.end();
        }

        function feedback() {
            const songId = song.id;
            let commentVersion = song.comment_version;
            if (commentVersion) {
                commentVersion += 1;
            } else {
                commentVersion = 1;
            }

            var query4 = `update song set comment_version=${commentVersion},comment_count=${commentCount} where id=${songId}`;
            console.log(query4);

            var connection4 = mysql.createConnection(mysqlCloudMusic);
            connection4.connect();
            connection4.query(query4, function (err, res) {
                if (err) {
                    console.log(err);

                } else {
                    console.log(res);
                    console.log();

                    setTimeout(() => {
                        getSong();
                    }, 1000);
                }
            });
            connection4.end();
        }
    }

    setTimeout(() => {
        process.exit();
    }, 3600 * 1000);
}
run();